package com.bolovan.infovaluta.reader;

import java.io.IOException;
import java.math.BigDecimal;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.bolovan.infovaluta.bean.ExchangeRate;
import com.bolovan.infovaluta.bean.ExchangeRateEntry;
import com.bolovan.infovaluta.bean.ExchangeRateSeller;
import com.bolovan.infovaluta.util.RateMaps;
import com.bolovan.infovaluta.util.RateUtil;

public class BnrReader extends ExchangeReader {

	public BnrReader(ExchangeRateSeller seller) {
		super(seller);
	}

	@Override
	public void buildRateMap(ExchangeRate map) throws IOException {
		fetchBNR(map);
	}

	private void fetchBNR(ExchangeRate map) throws IOException {
		Document doc = RateUtil.getDocument(ExchangeRateSeller.BNR.getUrl());
		setDate(doc.select("cube[date]").last().attr("date"));
		setParsingDate(RateMaps.date);
		Elements rates = doc.select("Rate");
		for (Element e : rates) {
			Integer multiplier = null;
			String multipl = e.attr("multiplier");
			if (multipl != null && !multipl.isEmpty()) {
				multiplier = Integer.valueOf(e.attr("multiplier"));
			}
			map.addToMap(new ExchangeRateEntry(e.attr("currency"), new BigDecimal(e.text()), null, multiplier));
		}
	}
}
